package cadchf;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import java.io.BufferedReader;
//import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
//import javax.swing.text.html.*;


/**
 * @author d60011
 *
 */
public class CadChfAnalyzer implements Runnable, ChangeListener {

	JTextField txtX0, txtA0, txtB0, txtC0, txtA1, txtB1, txtC1, txtBreakeven, txtTotalProfit, txtRelativeProfit;
	double pfFees = 2;
	double vcFees = 15;
	double X0, a0, b0, c0, a1, b1, c1, vBid, vAsk, pBid, pAsk, spot;
	JSlider sldrX0; 
	Color bgColor = new Color(200,200,255);
	JTextField txtBid;

	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {

		JFrame frame = new JFrame("CAD/CHF Analyzer");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


		sldrX0 = new JSlider(SwingConstants.HORIZONTAL,
				0, 20000, 500);
		//X0Slider.setBorder(BorderFactory.createEmptyBorder(0,0,10,0));
		sldrX0.addChangeListener(this);
		sldrX0.setMajorTickSpacing(5000);
		sldrX0.setMinorTickSpacing(500);
		sldrX0.setPaintTicks(true);
		sldrX0.setPaintLabels(true);
		sldrX0.setPreferredSize(new Dimension(600, 70));
		JLabel sliderLabel = new JLabel("Initial investment: ");
		txtX0 = new JTextField("");
		txtX0.setText(Integer.toString(sldrX0.getValue()));
		txtX0.setPreferredSize(new Dimension(50,20));
		JPanel X0Panel = new JPanel();
		X0Panel.add(sliderLabel);
		X0Panel.add(txtX0);
		X0Panel.add(sldrX0);

		this.setVCRates();
		this.setPFRates();
		this.setSpotRate();
		a0 = pAsk;
		b1 = vBid;
		JPanel pFPanel = PFPanel();
		//pFPanel.setBorder(BorderFactory.createLineBorder(new Color(255, 0, 0))); 
		JPanel vCPanel = VCPanel();
		JPanel spotPanel = SpotPanel();
		JPanel resultPanel = ResultPanel();
		JPanel futurePanel = futureRatesPanel();

		//JLabel ratesLabel = new JLabel("Current rate 1 cad in chf:       ", JLabel.LEFT);   	
		//JLabel ratesLabel1 = new JLabel("Future rate 1 cad in chf:         ", JLabel.LEFT);

		frame.setLayout(new FlowLayout(FlowLayout.LEFT));
		Container pane = frame.getContentPane();
		pane.add(X0Panel);
		pane.add(pFPanel);
		pane.add(new emptyContainer(500, 1)); //to force new line
		pane.add(vCPanel);
		pane.add(new emptyContainer(500, 1)); //to force new line
		pane.add(spotPanel);
		pane.add(new emptyContainer(500, 1)); //to force new line
		pane.add(new emptyContainer(900, 50)); //to force new line
		pane.add(futurePanel);
		pane.add(new emptyContainer(200, 1)); //to force new line
		pane.add(resultPanel);
		pane.add(new emptyContainer(200, 1)); //to force new line
		
		
		String btnLablel = "<html> <center>Go to <br> <i> http://www.google.ca/finance?q=CADCHF </i></center></html>";
		String urlCadChf = "http://www.google.ca/finance?q=CADCHF";
		JButton webLink = new JButton(btnLablel);
		webLink.addActionListener(new webLinkClick(urlCadChf));
		pane.add(webLink); 
		pane.setBackground(bgColor);

		frame.pack();
		frame.setVisible(true);
		frame.setSize(new Dimension(900, 500));
		frame.setLocation(400,50);  
		
		
		
		// open the default web browser for the HTML page
		

	}

	public String readURL(String urlIn) {
		try {
			URL u = new URL(urlIn);
			URLConnection yc = u.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(yc
					.getInputStream()));
			String inputLine;
			String out = new String("");

			while ((inputLine = in.readLine()) != null) {
				out = out + inputLine;
			}
			in.close();
			return out;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	public void setVCRates(){
		//get exchange rates from Vancity
		String VCcurrencies = readURL("https://www.vancity.com/Banking/ForeignExchange/Rates/");
		int ind = VCcurrencies.indexOf("Switzerland");    	
		String sB1 = VCcurrencies.substring(ind +44, ind + 52);
		double value = 1/Double.parseDouble(sB1);
		vBid = (double)Math.round(value * 10000) / 10000;
		String sA1 = VCcurrencies.substring(ind +78, ind + 86);
		value = 1/Double.parseDouble(sA1);
		vAsk = (double)Math.round(value * 10000) / 10000;
	}

	public void setPFRates(){
		//get exchange rates from Postfinance
		String PFcurrencies = readURL("https://www.postfinance.ch/de/priv/prod/pay/abroad/currency.html");
		String[] PFcurrenciesSplited = PFcurrencies.split("</td>");
		int i = 0;
		while (PFcurrenciesSplited[i+1].indexOf("Kanadischer Dollar") <0 || PFcurrenciesSplited[i].indexOf("CAD") <0){
			i++;
		}
		String sB0 = PFcurrenciesSplited[i+3];
		sB0 = sB0.replace("<td class=\"right\">", "");
		pBid = Double.parseDouble(sB0.trim());
		String sA0 = PFcurrenciesSplited[i+4];
		sA0 = sA0.replace("<td class=\"right\">", "");
		pAsk = Double.parseDouble(sA0.trim());
	}
	public void setSpotRate(){
		//get exchange rates from Yahoo
		String Yrate = readURL("http://finance.yahoo.com/q?s=CADCHF=X");
		int ind = Yrate.indexOf("yfs_l10_cadchf=x");    	
		String sC0 = Yrate.substring(ind +18, ind + 24);
		spot = Double.parseDouble(sC0);
	}

	public JPanel VCPanel(){
		JLabel label = new JLabel("Vancity rates: ", SwingConstants.LEFT);
		label.setPreferredSize(new Dimension(120,20));
		JLabel lblAsk = new JLabel("ask: ", SwingConstants.LEFT);
		JLabel lblBid = new JLabel("bid: ", SwingConstants.LEFT);
		JTextField txtAsk = new JTextField(Double.toString(vAsk));
		txtAsk.setPreferredSize(new Dimension(50,20)); 	
		JTextField txtBid = new JTextField(Double.toString(vBid));
		txtBid.setPreferredSize(new Dimension(50,20));
		//txtBid.getDocument().addDocumentListener(new TxtChange() );
		JPanel panel = new JPanel();
		panel.add(label);
		panel.add(lblBid);
		panel.add(txtBid);
		panel.add(lblAsk);
		panel.add(txtAsk);
		//panel.setPreferredSize(new Dimension(430,100));
		return panel;
	}
	public JPanel PFPanel(){
		JLabel label = new JLabel("Postfinance rates: ", SwingConstants.LEFT);
		label.setPreferredSize(new Dimension(120,20));
		JLabel lblAsk = new JLabel("ask: ", SwingConstants.LEFT);
		JLabel lblBid = new JLabel("bid: ", SwingConstants.LEFT);
		JTextField txtAsk = new JTextField(Double.toString(pAsk));
		txtAsk.setPreferredSize(new Dimension(50,20)); 	
		JTextField txtBid = new JTextField(Double.toString(pBid));
		txtBid.setPreferredSize(new Dimension(50,20));
		JPanel panel = new JPanel();
		panel.add(label);
		panel.add(lblBid);
		panel.add(txtBid);
		panel.add(lblAsk);
		panel.add(txtAsk);
		//panel.setPreferredSize(new Dimension(600, 50));
		return panel;
	}
	public JPanel SpotPanel(){
		JLabel label = new JLabel("Current spot rate:         ", SwingConstants.LEFT);
		JTextField txtSpot = new JTextField(Double.toString(spot));
		txtSpot.setPreferredSize(new Dimension(50,20));
		JPanel panel = new JPanel();
		panel.add(label);
		panel.add(txtSpot);
		//panel.setPreferredSize(new Dimension(430,100));
		return panel;
	}
	public JPanel futureRatesPanel(){
		JLabel label = new JLabel("Assumed future rates: ", SwingConstants.LEFT);
		//label.setPreferredSize(new Dimension(120,20));
		JLabel lblAsk = new JLabel("ask: ", SwingConstants.LEFT);
		JLabel lblBid = new JLabel("bid: ", SwingConstants.LEFT);
		JTextField txtAsk = new JTextField();
		txtAsk.setPreferredSize(new Dimension(50,20)); 	
		txtBid = new JTextField();
		txtBid.setPreferredSize(new Dimension(50,20));
		txtBid.getDocument().addDocumentListener(new TxtChange() );
		JPanel panel = new JPanel();
		panel.add(label);
		panel.add(lblBid);
		panel.add(txtBid);
		panel.add(lblAsk);
		panel.add(txtAsk);
		//panel.setPreferredSize(new Dimension(600, 50));
		return panel;
	}
	public JPanel ResultPanel(){
		JLabel breakevenLabel = new JLabel("Breakeven:  ", SwingConstants.LEFT);
		txtBreakeven = new JTextField( Double.toString(breakEven()) );
		txtBreakeven.setPreferredSize(new Dimension(100,20));
		JLabel totalProfitLabel = new JLabel("     Total Profit/Loss:  ", SwingConstants.LEFT);
		txtTotalProfit = new JTextField(Double.toString(totalProfit()));
		txtTotalProfit.setPreferredSize(new Dimension(100,20));
		JLabel relativeProfitLabel = new JLabel("     Rate of return (given time period):  ", SwingConstants.LEFT);
		txtRelativeProfit = new JTextField(Double.toString(relativeProfit()));
		txtRelativeProfit.setPreferredSize(new Dimension(100,20));
		JPanel panel = new JPanel();
		panel.add(breakevenLabel);
		panel.add(txtBreakeven);
		panel.add(totalProfitLabel);
		panel.add(txtTotalProfit);
		panel.add(relativeProfitLabel);
		panel.add(txtRelativeProfit);
		//panel.setPreferredSize(new Dimension(700,100));
		return panel;
	}

	public double breakEven(){
		double value = (-pfFees*a0 -vcFees* b1) / (a0 - b1);
		return (double)Math.round(value * 100) / 100;
	}
	public double totalProfit(){
		double value = -pfFees +(-vcFees + sldrX0.getValue() / a0 ) * b1 - sldrX0.getValue();
		return (double)Math.round(value * 100) / 100;
	}
	public double relativeProfit(){
		double value = this.totalProfit()/sldrX0.getValue();
		return (double)Math.round(value * 10000) / 10000;
	}

	public void reCalculate(){
		txtBreakeven.setText( Double.toString(breakEven()) );
		txtTotalProfit.setText( Double.toString(totalProfit()) );
		txtRelativeProfit.setText( Double.toString(relativeProfit()) );
	}

	public class TxtChange implements DocumentListener {  

		@Override
		public void changedUpdate(DocumentEvent e) {
			b1 = Double.parseDouble(txtBid.getText() );
			reCalculate();
		}
		@Override
		public void removeUpdate(DocumentEvent e) {
			b1 = Double.parseDouble(txtBid.getText() );
			reCalculate();
		}
		@Override
		public void insertUpdate(DocumentEvent e) {
			b1 = Double.parseDouble(txtBid.getText() );
			reCalculate();
		}   	
	}
	public class webLinkClick implements ActionListener{
		String url;
		webLinkClick(String s){
			super();
			url = s;
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			try {
				Desktop.getDesktop().browse(URI.create(url));
			} catch (IOException ex) {
				// TODO Auto-generated catch block
				ex.printStackTrace();
			}			
		}
	}

	@SuppressWarnings("serial")
	public class emptyContainer extends Container{    	
		public emptyContainer(int length, int width){
			super();
			this.setPreferredSize(new Dimension(length, width));
		}
	}

	@Override
	public void stateChanged(ChangeEvent e) {
		JSlider source = (JSlider)e.getSource();
		if (!source.getValueIsAdjusting()) {
			int val = source.getValue();
			txtX0.setText(Integer.toString(val));
			this.reCalculate();
		}
	}

	public static void main(String[] args) {
		CadChfAnalyzer analyzer = new CadChfAnalyzer();
		// Schedules the application to be run at the correct time in the event queue.
		SwingUtilities.invokeLater(analyzer);      
	}


}
